package com.zr.domain.sp.tool.migration.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MigrationDataService {

    @Autowired
    @Qualifier("sourceJdbcTemplate")
    private JdbcTemplate sourceJdbcTemplate;

    @Autowired
    @Qualifier("targetJdbcTemplate")
    private JdbcTemplate targetJdbcTemplate;

    public void migrateData() {

        int pageNumber = 1;
        int pageSize = 2;

        while (true) {
            // 查询源数据库
            String querySql = "SELECT * FROM class_table limit %d offset %d";
            String format = String.format(querySql, pageSize, pageSize * (pageNumber - 1));
            List<Map<String, Object>> sourceData = sourceJdbcTemplate.queryForList(format);
            // 准备插入目标数据库的SQL和参数
            String insertSql = "INSERT INTO TargetTable (column1, column2) VALUES (:column1, :column2)";
            for (Map<String, Object> row : sourceData) {
                Map<String, Object> params = new HashMap<>();
                params.put("column1", row.get("column1"));
                params.put("column2", row.get("column2"));

                // 插入目标数据库
                targetJdbcTemplate.update(insertSql, params);
            }

            if (sourceData.size() < pageSize) {
                break;
            }
        }
    }
}
